package operation

import (
	"../common"
	"../web"
	"encoding/json"
	"strconv"
	"strings"
)

type OperSplitObj struct {
	common.BaseHandler
}

type OperSplitDetailObj struct {
	common.BaseHandler
}

func (self *OperSplitObj) ParameterCheck() bool {
	return true
}

func (self *OperSplitObj) SqlExecute() bool {
	return true
}

func SplitBoxHandler(ctx *web.Context) {
	self := new(OperSplitObj)
	self.Ctx = ctx
	self.Html = "splitbox.html"
	self.Rightlist = []string{"splitbox"}
	self.DoQueryUrl(self)
}

func (self *OperSplitDetailObj) ParameterCheck() bool {
	s_obox := strings.TrimSpace(self.Ctx.Params["oldbox"])
	s_nbox := strings.TrimSpace(self.Ctx.Params["boxid"])
	s_bqty := strings.TrimSpace(self.Ctx.Params["baseqty"])
	s_ssns := strings.TrimSpace(self.Ctx.Params["ssn"])
	err := ""
	if s_obox == "" {
		err = common.GetText(self.Lang, "Please input the Source Box.")
	}
	if s_nbox == "" {
		err = common.GetText(self.Lang, "Please input the Target Box.")
	}
	i_qty, errs := strconv.Atoi(s_bqty)
	if errs != nil {
		err = common.GetText(self.Lang, "BOX Qty must be a numeric.")
	}
	if i_qty < 1 {
		err = common.GetText(self.Lang, "Qty must be more than zero.")
	}
	if s_ssns == "" {
		err = common.GetText(self.Lang, "Please input the Product No.")
	}
	if s_obox == s_nbox {
		err = common.GetText(self.Lang, "Can't Split Box to itself.")
	}
	packedqty := "0"
	if s_nbox != "" {
		iRtnData := *common.FetchOneRowPtr(
			`SELECT TOP 1 ISNULL(PACKEDQTY, 0) 
	           FROM SFC_BOX(NOLOCK) 
	          WHERE BOXID=?`,
			self.Usr.Conn, new(common.RecDataStr), s_nbox)
		packedqty = iRtnData.(common.RecDataStr).Data
	}
	if err != "" {
		dict_js, _ := json.Marshal(map[string]string{"result": err, "packedqty": packedqty})
		self.Ctx.ResponseWriter.Write(dict_js)
		return false
	}

	self.Sqlparas = append(self.Sqlparas, s_obox)
	self.Sqlparas = append(self.Sqlparas, s_nbox)
	self.Sqlparas = append(self.Sqlparas, i_qty)
	self.Sqlparas = append(self.Sqlparas, s_ssns)
	self.Sqlparas = append(self.Sqlparas, self.Usr.Username)

	return true
}

func (self *OperSplitDetailObj) SqlQueryExecute() {
	err := ""
	spRtnData := *common.FetchOneRowPtr(
		`sp_SplitBox ?, ?, ?, ?, ?`,
		self.Usr.Conn, new(common.SPReturn), self.Sqlparas...)
	if spRtnData.(common.SPReturn).Flag > 0 {
		err = common.GetTextSP(self.Lang, spRtnData)
	}

	iRtnData := *common.FetchOneRowPtr(
		`SELECT TOP 1 ISNULL(PACKEDQTY, 0) 
           FROM SFC_BOX(NOLOCK) 
          WHERE BOXID=?`,
		self.Usr.Conn, new(common.RecDataStr), self.Sqlparas[1].(string))
	packedqty := iRtnData.(common.RecDataStr).Data

	dict_js, _ := json.Marshal(map[string]string{"result": err, "packedqty": packedqty})
	self.Ctx.ResponseWriter.Write(dict_js)
}

func SplitBoxOperHandler(ctx *web.Context) {
	self := new(OperSplitDetailObj)
	self.Ctx = ctx
	self.DoJson(self)
}
